<template>
  <div class="food-edit">
    <div class="form-container">
      <h2>{{ food.foodId ? '编辑食品' : '添加新食品' }}</h2>
      
      <div class="form-group">
        <label>食品名称</label>
        <input type="text" v-model="food.foodName" placeholder="请输入食品名称">
      </div>
      
      <div class="form-group">
        <label>食品描述</label>
        <textarea v-model="food.foodExplain" placeholder="请输入食品描述"></textarea>
      </div>
      
      <div class="form-group">
        <label>食品价格</label>
        <input type="number" v-model="food.foodPrice" placeholder="请输入价格">
      </div>
      
      <div class="form-group">
        <label>食品图片</label>
        <input type="text" v-model="food.foodImg" placeholder="图片URL">
        <div v-if="food.foodImg" class="image-preview">
          <img :src="food.foodImg" alt="食品图片预览">
        </div>
        <button @click="showImageUpload = true">上传图片</button>
      </div>
      
      <div class="form-actions">
        <button class="save-btn" @click="saveFood">保存</button>
        <button class="cancel-btn" @click="cancel">取消</button>
      </div>
    </div>
    
    <!-- 图片上传弹窗 -->
    <div v-if="showImageUpload" class="image-upload-modal">
      <div class="modal-content">
        <h3>上传食品图片</h3>
        <input type="file" @change="handleImageUpload" accept="image/*">
        <button @click="showImageUpload = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FoodEdit',
  data() {
    return {
      food: {
        foodId: null,
        foodName: '',
        foodExplain: '',
        foodImg: '',
        foodPrice: 0,
        businessId: null
      },
      showImageUpload: false
    };
  },
  created() {
    const business = this.$getSessionStorage('business');
    if (!business) {
      this.$router.push('/businessLogin');
      return;
    }
    
    this.food.businessId = business.businessId;
    
    // 如果是从编辑进入，加载食品数据
    if (this.$route.query.foodId) {
      this.loadFood(this.$route.query.foodId);
    }
  },
  methods: {
    async loadFood(foodId) {
      try {
        const response = await this.$axios.post(
          'FoodController/getFoodById', 
          this.$qs.stringify({ foodId })
        );
        
        if (response.data) {
          this.food = response.data;
        } else {
          alert('加载食品信息失败');
        }
      } catch (error) {
        console.error('加载食品信息出错:', error);
        alert('加载食品信息出错');
      }
    },
    
    async saveFood() {
      // 验证必填字段
      if (!this.food.foodName) {
        alert('食品名称不能为空');
        return;
      }
      
      if (!this.food.foodPrice || this.food.foodPrice <= 0) {
        alert('请输入有效的价格');
        return;
      }
      
      try {
        const api = this.food.foodId ? 
          'FoodController/updateFood' : 'FoodController/saveFood';
        
        const response = await this.$axios.post(
          api, 
          this.$qs.stringify(this.food)
        );
        
        // 后端返回的是 Map 对象，使用解构获取值
        const { code, message, affectedRows } = response.data;
        
        if (code === 200) {
          alert(message || (this.food.foodId ? '食品更新成功' : '食品添加成功'));
          console.log(`操作影响行数: ${affectedRows}`);
          this.$router.push('/foodManage');
        } else if (code === 400) {
          alert(`操作失败: ${message || '未知错误'}`);
        } else if (code === 500) {
          alert(`服务器错误: ${message}`);
          console.error('服务器错误详情:', response.data);
        }
      } catch (error) {
        console.error('保存食品出错:', error);
        
        if (error.response) {
          // 处理 HTTP 错误状态码
          const { status, data } = error.response;
          alert(`请求错误 (${status}): ${data.message || '未知错误'}`);
        } else {
          alert('网络错误或请求未发送');
        }
      }
    },
    
    cancel() {
      this.$router.push('/foodManage');
    },
    
    handleImageUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 简单实现 - 实际项目中应使用Base64或上传到服务器
      const reader = new FileReader();
      reader.onload = (e) => {
        this.food.foodImg = e.target.result;
        this.showImageUpload = false;
      };
      reader.readAsDataURL(file);
    }
  }
};
</script>

<style scoped>
.food-edit {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-container {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
}

.form-group {
  margin-bottom: 25px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #34495e;
}

input, textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus, textarea:focus {
  border-color: #3498db;
  outline: none;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

.image-preview {
  margin-top: 10px;
  max-width: 300px;
}

.image-preview img {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #eee;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

button {
  padding: 12px 25px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.save-btn {
  background-color: #27ae60;
  color: white;
}

.save-btn:hover {
  background-color: #219653;
}

.cancel-btn {
  background-color: #e74c3c;
  color: white;
}

.cancel-btn:hover {
  background-color: #c0392b;
}

/* 图片上传模态框 */
.image-upload-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.modal-content h3 {
  margin-top: 0;
}
</style>